package com.my.lock.v8;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicSemaphore {
    private static final Logger LOGGER = LoggerFactory.getLogger(AtomicSemaphore.class);

    public static void main(String[] args) throws Exception {
        AtomicInteger semaphore = new AtomicInteger(0);

        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    int value = semaphore.get();
                    if (value < 7 && semaphore.compareAndSet(value, value + 1)) {
                        LOGGER.info("success to get lock...");
                    }
                }
            });
            threads.add(thread);
            thread.start();
        }

        for (Thread thread : threads) {
            thread.join();
        }

        LOGGER.info("semaphore: {}", semaphore);
    }
}
